package org.dreamwork.assistant.tools.network.gui;

import org.dreamwork.util.Tools;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * Created by seth.yang on 2018/5/9
 */
public class UdpReader extends NetworkReader {
    private DatagramSocket socket;
    private DatagramPacket packet;
    private boolean running = true;

    UdpReader (DatagramSocket socket, DatagramPacket packet/*, IMessageLogger logger*/) {
        super (/*logger, */"UDPReader");
        this.socket = socket;
        this.packet = packet;
    }

    @Override
    protected void doWork () {
        try {
            while (running) {
                socket.receive (packet);
                if (packet.getLength () > 0) {
                    byte[] data = Tools.slice (packet.getData (), packet.getOffset (), packet.getLength ());
//                    logger.append (data);

                    if (listener != null) {
                        listener.onReceived (data);
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace ();
        } finally {
            if (socket != null)
                socket.close ();
        }
    }

    @Override
    public void shutdown () {
        running = false;
    }
}